import type { RouteRecordRaw } from 'vue-router';
import type { MenuRaw } from '@/types/sys/menu';
import { getLayout } from '@/layouts';

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.vue');

const loadView = (component: string) => {
  const key = `/src/views/${component}.vue`.replace('//', '/');
  if (key in modules) {
    return modules[key];
  }
  return () => {};
};

/**
 * 构建路由
 * @param routes 菜单
 * @returns
 */
export const buildAsyncRoutes = (menus: MenuRaw[] = []): RouteRecordRaw[] => {
  return menus.map((menu) => {
    const { type, path, name, component, redirect, title, icon, hidden, children, activateRoute } = menu;
    // 外链
    if (type === 'link') {
      return {
        path,
        name,
        component: () => {},
        meta: {
          title,
          icon,
          hidden
        }
      } as RouteRecordRaw;
    }
    // 目录
    if (type === 'dir') {
      return {
        path,
        name,
        component: getLayout(component),
        redirect,
        meta: {
          title,
          icon,
          hidden,
          activateRoute
        },
        children: children ? buildAsyncRoutes(children) : []
      } as RouteRecordRaw;
    }
    return {
      path,
      name,
      component: loadView(component),
      meta: {
        title,
        icon,
        hidden,
        activateRoute
      }
    } as RouteRecordRaw;
  });
};
